<?php

namespace App\Service\playlet;
use App\Model\Playlet;
use App\Service\CommicService;
use App\Model\PlayletBlocksRanking;
use App\Model\Applet;

use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
class PlayletBlocksRankingService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }
    const STATUS_ENABLE  = 1;

    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $status      = $params['status'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;

        $query = PlayletBlocksRanking::query()->select(['id','name','created_at','updated_at']);

        if ($keyword) {
            $query->orWhere([['name', 'like', '%'.$keyword.'%']]);
        }
        if ($status != '') {
            $query->where(['status' => $status]);
        }
        $query->where(['deleted' => 0]);
        $query->whereIn('template_type',[103,105]);
        $query->whereIn('id',[3,5]);
        $models = $query->paginate($pageSize,['*'],'page',$page);

        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            $data['playlet_name']  = '公共配置';
            $selectData[] =$data;
        }
        $data = $models->toArray();
        $data['data'] = $selectData;
        return $data;
    }

    public function createOrUpdate(Array $postData,bool $is_update = false,PlayletBlocksRanking $appletBlocksRankingInfo = null){

        $playlet_ids = $postData['playlet_ids'];

        $playletIds = Playlet::query()->whereIn('id',$playlet_ids)->select(['id'])->get()->toArray();
        if(empty($playletIds)){
            return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
        }
        if(count($playlet_ids) != count($playletIds)){
            return $this->response(SystemCode::SYSTEM_ERROR, '短剧部分不存在');
        }

        $model = $appletBlocksRankingInfo;
        $model->playlet_ids = implode(',',$playlet_ids);

        if($model->save()){
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
        }
    }


    public function combination($playletIdsArr,$playletInfo){

        $playletKeyVal = array();

        foreach ($playletInfo as $item){
            $playletKeyVal[$item['id']] = $item;
        }

        $returnData = array();
        foreach ($playletIdsArr as $value){

            if(!empty($playletKeyVal[$value])){
                $returnData[] = $playletKeyVal[$value];
            }
        }
        return $returnData;
    }
}